package com.xincheng.shuimalong.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.xlog.XLog;
import com.xincheng.library.xswipemenurecyclerview.Mode;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.listener.OnLoadingListener;
import com.xincheng.library.xswipemenurecyclerview.recycler.MRecyclerView;
import com.xincheng.library.xswipemenurecyclerview.recycler.XRecyclerView;
import com.xincheng.library.xswipemenurecyclerview.widget.ProgressStyle;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.MainActivity;
import com.xincheng.shuimalong.activity.SearchActivity;
import com.xincheng.shuimalong.activity.config.CitySelectActivity;
import com.xincheng.shuimalong.activity.config.InsuranceCompanyActivity;
import com.xincheng.shuimalong.activity.insurance.UserHomeActivity;
import com.xincheng.shuimalong.activity.market.MarketFillInsuranceActivity;
import com.xincheng.shuimalong.activity.market.MarketFilterActivity;
import com.xincheng.shuimalong.activity.recept.MyAcceptanceActivity;
import com.xincheng.shuimalong.adapter.market.MarketAdapter;
import com.xincheng.shuimalong.adapter.market.MarketSortAdapter;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RefreshStatus;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.market.Market;
import com.xincheng.shuimalong.entity.market.MarketSort;
import com.xincheng.shuimalong.entity.user.UserInfo;
import com.xincheng.shuimalong.listener.ItemButtonClickListener;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.CardItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xuhao on 2017/6/13.
 * 市场
 */

public class MarketFragment extends BaseFragment implements MainActivity.ConfigCallBack {
    @BindView(R.id.market_rv)
    XRecyclerView mMarketRv;
    @BindView(R.id.market_sort_tv)
    TextView mMarketSortTv;
    @BindView(R.id.market_head_layout)
    LinearLayout mHeadLayout;
    @BindView(R.id.market_insurance_company_tv)
    TextView mCompanyTv;
    @BindView(R.id.market_issue_receipt_bill_btn)
    StateButton mIssueReceiptBillBtn;

    private final ThreadLocal<List<Market.Data>> mMarketList = new ThreadLocal<>();
    private MarketAdapter mMarketAdapter;
    private List<CommonConfig> mCarTypes;

    private PopupWindow mSortPoup;
    private MRecyclerView mSortRv;
    private MarketSortAdapter mSortAdapter;
    private int[] mScreens;

    private int mCarTypeId;
    private int mCityId;
    private int mProvinceId;
    private int mCompanyId;
    private int mMinReturn;
    private int mMaxReturn;
    private String mOrder = "";
    private String mKeyword = "";
    private boolean mShowNewCar;
    private int mNewCarId;
    private int mUseAge;
    private int mPage;
    private RefreshStatus mRefreshStatus;
    private CommonConfig mCompany;
    private int mGoStatus;
    private Market.Data mMarketData;

    @Override
    public int getFragmentLayoutId() {
        return R.layout.fragment_market;
    }

    private void initConfig() {
        mCityId = 213;
        mProvinceId = 0;
        mCompanyId = 0;
        mOrder = "";
    }

    private void initSearchData() {
        mCarTypeId = 1;
        mMinReturn = -1;
        mMaxReturn = -1;
        mPage = 1;
        mShowNewCar = false;
        mNewCarId = 0;
        mKeyword = "";
        mUseAge = 0;
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        mMarketSortTv.setText(getString(R.string.market_sort));
        mCompanyTv.setText(getString(R.string.insurance_company));
    }

    @Override
    public void initData() {
        mCarTypes = ConfigUtil.getCommonConfigList(getActivity(), PrefKey.CAR_TYPE);
        mMarketRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mMarketRv.addItemDecoration(new CardItemDecoration());
        mMarketRv.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mMarketRv.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mMarketRv.setArrowImageView(R.drawable.iconfont_downgrey);
        mMarketAdapter = new MarketAdapter(getActivity(),
                GlideOptionsManager.getInstance().getRequestOptions());
        mMarketAdapter.setCarTypeList(mCarTypes);
        mMarketRv.setAdapter(mMarketAdapter);
        mMarketRv.setMode(Mode.BOTH);
        ((MainActivity) getActivity()).registerConfigCallBack(this);
        initMarketTitleBar(mCarTypes);
        initPopupWindow();
        initConfig();
        initSearchData();
        searchAcceptance();
    }

    private void initPopupWindow() {
        mScreens = UIUtil.getDisplaySize(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.market_sort_popup, null);
        mSortPoup = CommonUtil.createPopupWindow(view);
        mSortRv = UIUtil.findViewById(view, R.id.market_sort_popup_mrv);
        mSortRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<MarketSort> sortList = new ArrayList<>();
        String[] sortArr = getResources().getStringArray(R.array.market_sort);
        for (int i = 0; i < sortArr.length; i++) {
            MarketSort marketSort = new MarketSort();
            marketSort.setId(i + 1);
            marketSort.setName(sortArr[i]);
            marketSort.setOrder(Constant.MARKET_SORT_ORDER[i]);
            marketSort.setSelected(i == 0 ? true : false);
            sortList.add(marketSort);
        }
        mSortAdapter = new MarketSortAdapter(getActivity(), sortList);
        mSortRv.setAdapter(mSortAdapter);
        mSortRv.setOnItemClickListener(new MyOnItemClickListener());
        UIUtil.findViewById(view, R.id.market_sort_popup_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSortPoup != null && mSortPoup.isShowing()) {
                    mSortPoup.dismiss();
                }
            }
        });
    }

    private void searchAcceptance() {
        BaseObserver observer = new BaseObserver(getActivity()) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                mMarketRv.setMode(Mode.BOTH);
                if (data != null) {
                    Market market = GsonUtil.parseData(data, Market.class);
                    List<Market.Data> dataList = market.getMarketList();
                    switch (mRefreshStatus) {
                        case LOAD_DEFAULT:
                            mMarketList.set(dataList);
                            break;
                        case PULL_TO_REFRESH:
                            mMarketRv.refreshComplete();
                            mMarketList.set(dataList);
                            break;
                        case LOAD_MORE:
                            mMarketRv.loadMoreComplete();
                            mMarketList.get().addAll(dataList);
                            break;
                    }
                    if (MyUtil.isDataLengthLess(dataList)) {
                        mMarketRv.setMode(Mode.PULL_TO_REFRESH);
                    }
                    mMarketAdapter.refreshData(mMarketList.get());
                }

            }
        };
        if (mRefreshStatus == RefreshStatus.LOAD_DEFAULT) {
            observer.initProgressDialog(getActivity(), getString(R.string.loading_data));
        }
        RetroSubscrube.getInstance().getSubscrube(GetParam.searchAcceptance(mCityId, mProvinceId, mCarTypeId,
                mCompanyId, mMinReturn, mMaxReturn, mOrder, mPage, mShowNewCar, mNewCarId, mUseAge, mKeyword),
                observer);
    }

    @Override
    public void addListener() {
        mTabLayout.addOnTabSelectedListener(new MyOnTabSelectedListener());
        mMarketRv.setOnLoadingListener(new MyOnLoadingListener());
        mMarketAdapter.setItemButtonClickListener(new MyItemButtonClickListener());
    }

    @Override
    public void parseCity(RegionData province, RegionData city, CommonConfig hotCity) {
        if (province != null) {
            mProvinceId = province.getId();
            mCityId = 0;
            if (mProvinceId == 0) {
                mCitySelectTv.setText(province.getName());
            } else {
                if (city != null) {
                    mCityId = city.getId();
                    if (mCityId == 0) {
                        mCitySelectTv.setText(province.getName());
                    } else {
                        mCitySelectTv.setText(city.getName());
                    }
                }
            }
        } else if (hotCity != null) {
            mCityId = hotCity.getId();
            mProvinceId = ConfigUtil.getCity(getActivity(), mCityId).getParentId();
            mCitySelectTv.setText(hotCity.getName());
        }
        ((MainActivity) getActivity()).setProvinceId(mProvinceId);
        ((MainActivity) getActivity()).setMarketCityId(mCityId);
        mPage = 1;
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        searchAcceptance();
    }

    @Override
    public void parseFilter(boolean showNewCar, int newCarId, int min, int max, int useAge) {
        mShowNewCar = showNewCar;
        mNewCarId = newCarId;
        mMinReturn = min;
        mMaxReturn = max;
        mUseAge = useAge;
        mPage = 1;
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        searchAcceptance();
    }

    @Override
    public void parseCompany(CommonConfig company) {
        if (company != null) {
            mCompany = company;
            mCompanyId = mCompany.getId();
            mCompanyTv.setText(mCompanyId == 0 ? getString(R.string.insurance_company) : mCompany.getName());
            mPage = 1;
            mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
            searchAcceptance();
        }
    }

    @Override
    public void parseKeyWord(String keyword) {
        if (!CommonUtil.isEmpty(keyword)) {
            mKeyword = keyword;
        }
        mPage = 1;
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        searchAcceptance();
    }

    @OnClick({R.id.common_city_select_tv, R.id.common_filter_iv, R.id.common_search_iv,
            R.id.market_issue_receipt_bill_btn, R.id.market_sort_layout, R.id.market_insurance_company_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_city_select_tv:
                Bundle extras = new Bundle();
                extras.putInt(IntentKey.FROM, 1);
                ShowActivity.showActivityForResult(getActivity(), CitySelectActivity.class, extras,
                        RequestCodeKey.GO_CITY_SELECT);
                break;
            case R.id.common_filter_iv:
                extras = new Bundle();
                extras.putInt(IntentKey.NEW_CAR_ID, mNewCarId);
                if (mMinReturn != -1) {
                    extras.putInt(IntentKey.MIN, mMinReturn);
                }
                if (mMaxReturn != -1) {
                    extras.putInt(IntentKey.MAX, mMaxReturn);
                }
                if (mUseAge != 0) {
                    extras.putInt(IntentKey.USE_AGE, mUseAge);
                }
                ShowActivity.showActivityForResult(getActivity(), MarketFilterActivity.class, extras,
                        RequestCodeKey.GO_MARKET_FILTER);
                break;
            case R.id.common_search_iv:
                extras = new Bundle();
                extras.putInt(IntentKey.FROM, 2);
                ShowActivity.showActivityForResult(getActivity(), SearchActivity.class, extras,
                        RequestCodeKey.GO_SEARCH);
                break;
            case R.id.market_issue_receipt_bill_btn:
                mGoStatus = 1;
                getUserInfo();
                break;
            case R.id.market_sort_layout:
                if (mSortPoup != null && !mSortPoup.isShowing()) {
                    mSortPoup.setWidth(mScreens[0]);
                    int height = CommonUtil.getStatusBarHeight(getActivity()) + mTitleBarLayout.getHeight()
                            + mHeadLayout.getHeight();
                    XLog.e("height->" + height);
                    mSortPoup.setHeight(mScreens[1] - height);
                    mSortPoup.showAsDropDown(mHeadLayout);
                }
                break;
            case R.id.market_insurance_company_layout:
                extras = new Bundle();
                extras.putInt(IntentKey.FROM, 1);
                if (mCompany != null) {
                    extras.putParcelable(IntentKey.INSURANCE_COMPANY, mCompany);
                }
                ShowActivity.showActivityForResult(getActivity(), InsuranceCompanyActivity.class, extras,
                        RequestCodeKey.GO_INSURANCE_COMPAY_SELECT);
                break;
        }
    }

    private class MyOnTabSelectedListener implements TabLayout.OnTabSelectedListener {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            initSearchData();
            mCarTypeId = mCarTypes.get(tab.getPosition()).getId();
            mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
            mPage = 1;
            searchAcceptance();
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    }

    private class MyItemButtonClickListener implements ItemButtonClickListener {

        @Override
        public void buttonClick(int clickId, int position) {
            switch (clickId) {
                case R.id.item_market_headicon_iv:
                    Bundle extras1 = new Bundle();
                    int userId = mMarketAdapter.getItem(position - Constant.ITEM_POSITION_MINUS).
                            getUserId();
                    extras1.putString(IntentKey.USER_ID, String.valueOf(userId));
                    extras1.putInt(IntentKey.FROM, 1);
                    ShowActivity.showActivity(getActivity(), UserHomeActivity.class, extras1);
                    break;
                case R.id.item_market_quotation_tv:
                    mMarketData = mMarketAdapter.getItem(position -
                            Constant.ITEM_POSITION_MINUS);
                    String currentUserId = PrefUtil.getString(getActivity(),
                            PrefKey.LOGIN_USER_ID, "");
                    if (currentUserId.equals(String.valueOf(mMarketData.getUserId()))) {
                        showToastMsg("不能对自己的订单申请报价");
                        return;
                    }
                    mGoStatus = 2;
                    getUserInfo();
                    break;
            }
        }
    }

    private void getUserInfo() {
        String token = PrefUtil.getString(getActivity(), PrefKey.TOKEN, "");
        String userId = PrefUtil.getString(getActivity(), PrefKey.LOGIN_USER_ID, "");
        RetroSubscrube.getInstance().getSubscrube(GetParam.getUserInfo(token, userId),
                new BaseObserver(getActivity(), getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            UserInfo userInfo = GsonUtil.parseData(data, UserInfo.class);
                            if (userInfo.isCert()) {
                                switch (mGoStatus) {
                                    case 1:
                                        ShowActivity.showActivity(getActivity(), MyAcceptanceActivity.class);
                                        break;
                                    case 2:
                                        Bundle extras = new Bundle();
                                        extras.putParcelable(IntentKey.MARKET_DATA, mMarketData);
                                        ShowActivity.showActivity(getActivity(), MarketFillInsuranceActivity.class,
                                                extras);
                                }
                            } else {
                                showIdentifyAlertView();
                            }
                        } else {
                            isGoFillReceiptInfo();
                        }

                    }

                    @Override
                    protected void onHandleError(String msg) {
                        isGoFillReceiptInfo();
                    }
                });
    }

    private void isGoFillReceiptInfo() {
        boolean isCert = PrefUtil.getBoolean(getActivity(), PrefKey.LOGIN_CERT, false);
        if (isCert) {
            ShowActivity.showActivity(getActivity(), MyAcceptanceActivity.class);
        } else {
            showIdentifyAlertView();
        }
    }

    private class MyOnLoadingListener implements OnLoadingListener {

        @Override
        public void onRefresh() {
            mRefreshStatus = RefreshStatus.PULL_TO_REFRESH;
            mPage = 1;
            searchAcceptance();
        }

        @Override
        public void onLoadMore() {
            mRefreshStatus = RefreshStatus.LOAD_MORE;
            mPage++;
            searchAcceptance();
        }
    }

    private class MyOnItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            MarketSort marketSort = mSortAdapter.getItem(position);
            mMarketSortTv.setText(marketSort.getName());
            mOrder = marketSort.getOrder();
            mSortAdapter.changeSelect(position);
            mSortPoup.dismiss();
            mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
            mPage = 1;
            searchAcceptance();
        }
    }
}
